package com.chenfengyao.gamereversi.util

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 * Created by 陈丰尧 on 1/9/21
 * 对协程的扩展方法
 */

// 在所有实现了LifecycleOwner接口的类中,可以直接使用launch方法
fun LifecycleOwner.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit,
) = lifecycleScope.launch(context, start, block)




// 在viewMode中可以直接使用launch
fun ViewModel.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit,
) = viewModelScope.launch(context, start, block)

fun AppCompatActivity.repeatOnCreate(block: suspend CoroutineScope.() -> Unit) {
    lifecycleScope.launch {
        lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED, block)
    }
}

fun AppCompatActivity.repeatOnStarted(block: suspend CoroutineScope.() -> Unit) {
    lifecycleScope.launch {
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED, block)
    }
}

fun AppCompatActivity.repeatOnResume(block: suspend CoroutineScope.() -> Unit) {
    lifecycleScope.launch {
        lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED, block)
    }
}

fun <T> AppCompatActivity.repeatCollectOnCreate(flow: Flow<T>, collector: FlowCollector<T>) {
    repeatOnCreate {
        flow.collect(collector)
    }
}

fun <T> AppCompatActivity.repeatCollectOnStarted(flow: Flow<T>, collector: FlowCollector<T>) {
    repeatOnStarted {
        flow.collect(collector)
    }
}

fun <T> AppCompatActivity.repeatCollectOnResume(flow: Flow<T>, collector: FlowCollector<T>) {
    repeatOnResume {
        flow.collect(collector)
    }
}


fun LifecycleService.repeatOnResume(block: suspend CoroutineScope.() -> Unit): Job {
    return launch {
        repeatOnLifecycle(Lifecycle.State.RESUMED, block)
    }
}

fun LifecycleService.repeatOnStart(block: suspend CoroutineScope.() -> Unit): Job {
    return launch {
        repeatOnLifecycle(Lifecycle.State.STARTED, block)
    }
}

fun <T> LifecycleService.repeatCollectOnResume(flow: Flow<T>, collector: FlowCollector<T>): Job {
    return repeatOnResume {
        flow.collect(collector)
    }
}

fun <T> LifecycleService.repeatCollectOnStart(flow: Flow<T>, collector: FlowCollector<T>): Job {
    return repeatOnStart {
        flow.collect(collector)
    }
}

